/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import com.apps.ubc.cc.model.BuildingModel;
import com.apps.utils.WrapperUtils;

public class UBCClassroomService {
	
	public UBCClassroomService(){
	}
	
	public String search(String code){
		String address = null;
		try {
			address = parseURLContent(getURLContentReader(),code);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return address;
	}
	
	private BufferedReader getURLContentReader()throws Exception {
		
		String 	url = "http://www.students.ubc.ca/classroomservices/buildings-and-classrooms/";
		return new BufferedReader(new InputStreamReader(
				new URL(url).openStream()));
	}

	private String parseURLContent(BufferedReader br, String search) throws IOException {
		
		String line = br.readLine();
		while(line != null){
			if(line.contains("<td><a href=\"?code=")){
				String code = WrapperUtils.stringInBwtn("<td><a href=\"?code=", "\" class", line);
				String location = WrapperUtils.stringInBwtn("\">", "</a></td>", line);
				if(search.equals(location) && code.equals(location)){
					line = br.readLine();
					line = br.readLine();
					return WrapperUtils.stringInBwtn("<td>", "</td>", line);
				}
				else if(search.equals(location)){
					line = br.readLine();
					return WrapperUtils.stringInBwtn("<td>", "</td>", line);
				}
				
			}
			line = br.readLine();
		}
		return null;
	}

}
